// frontend/UserInterface.java
package frontend.user;

import backend.GeneralDatabase;
import backend.DiseaseItem;
import backend.EmptyOutput;
import service.DatabaseManager;
import service.User.UserService;
import service.User.QueryResult;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

public class UserInterface extends JFrame {
    private final UserService userService;
    private DiseaseListPanel diseaseListPanel;
    private DiseaseInfoPanel diseaseInfoPanel;
    private String currentDiseaseCategory;
    private String[] departmentNames;

    public UserInterface() throws Exception {
        // 初始化服务层
        this.userService = new UserService(DatabaseManager.getInstance());

        try {
            // 获取所有科室名称
            departmentNames = userService.getAllDepartments();
            if (departmentNames.length == 0) {
                JOptionPane.showMessageDialog(this, "请先添加科室数据");
                return;
            }
            currentDiseaseCategory = departmentNames[0]; // 默认选中第一个科室
        } catch (EmptyOutput e) {
            JOptionPane.showMessageDialog(this, "无法连接数据库或无科室数据");
            e.printStackTrace();
            return;
        }

        // 初始化面板
        diseaseListPanel = new DiseaseListPanel();
        diseaseInfoPanel = new DiseaseInfoPanel(null); // 初始为空

        // 设置UI布局
        setTitle("用户界面");
        setSize(1500, 800);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 创建顶部导航栏
        TopNavigationBar topNavigationBar = new TopNavigationBar(departmentNames);

        // 添加搜索框
        SearchPanel searchPanel = new SearchPanel();
        searchPanel.addPropertyChangeListener("search", e -> {
            String keyword = (String) e.getNewValue();
            handleSearch(keyword);
        });

        topNavigationBar.add(searchPanel, BorderLayout.EAST);
        add(topNavigationBar, BorderLayout.NORTH);

        // 设置标签点击监听器
        topNavigationBar.setOnTabSelectedListener(this::handleDepartmentChange);

        // 加载默认科室数据
        loadAndSetDiseases(currentDiseaseCategory);

        // 添加滚动面板
        JScrollPane scrollPane = new JScrollPane(diseaseListPanel);
        scrollPane.setPreferredSize(new Dimension(200, 0));
        add(scrollPane, BorderLayout.WEST);

        // 添加疾病信息展示面板
        add(diseaseInfoPanel, BorderLayout.CENTER);

        // 添加底部退出按钮
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 20, 10));
        JButton logoutButton = new JButton("退出登录");
        logoutButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        logoutButton.setBackground(new Color(255, 99, 71));
        logoutButton.setForeground(Color.WHITE);
        logoutButton.setFocusPainted(false);

        logoutButton.addActionListener(e -> {
            int confirm = JOptionPane.showConfirmDialog(
                    this,
                    "确定要退出登录吗？",
                    "退出确认",
                    JOptionPane.YES_NO_OPTION
            );
            if (confirm == JOptionPane.YES_OPTION) {
                dispose();
                SwingUtilities.invokeLater(() -> {
                    try {
                        new frontend.Login().setVisible(true);
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                });
            }
        });

        bottomPanel.add(logoutButton);
        add(bottomPanel, BorderLayout.SOUTH);

        setVisible(true);
    }

    private void handleSearch(String keyword) {
        if (keyword.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入搜索关键词");
            return;
        }

        QueryResult<DiseaseItem[]> result = userService.performSearch(keyword);
        switch (result.getStatus()) {
            case SUCCESS:
                diseaseListPanel.updateDiseaseList(Arrays.asList(result.getData()));
                break;

            case ERROR:
                JOptionPane.showMessageDialog(this, result.getErrorMessage());
                diseaseListPanel.updateDiseaseList(new ArrayList<>());
                break;
        }
    }

    private void handleDepartmentChange(String departmentName) {
        currentDiseaseCategory = departmentName;
        loadAndSetDiseases(departmentName);
    }

    private void loadAndSetDiseases(String departmentName) {
        QueryResult<DiseaseItem[]> result = userService.queryDiseasesByDepartment(departmentName);
        switch (result.getStatus()) {
            case SUCCESS:
                diseaseListPanel.updateDiseaseList(Arrays.asList(result.getData()));
                break;

            case ERROR:
                JOptionPane.showMessageDialog(this, result.getErrorMessage());
                diseaseListPanel.updateDiseaseList(new ArrayList<>());
                break;
        }

        // 更新疾病信息面板
        diseaseListPanel.addListSelectionListener(e -> {
            DiseaseItem selected = diseaseListPanel.getSelectedDisease();
            if (selected != null) {
                remove(diseaseInfoPanel);
                diseaseInfoPanel = new DiseaseInfoPanel(selected);
                add(diseaseInfoPanel, BorderLayout.CENTER);
                revalidate();
                repaint();
            }
        });
    }
}
